﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YBApproval.Model;
using YBApproval.IDAL;
using YBApproval.BLL;
using YBApproval.UserControls;
using YBApproval.Common;

namespace YBApproval.Pages
{
    public partial class Approval : System.Web.UI.Page
    {
        private string _recordId = "";
        private Instance _inst = null;
        private List<InstanceApproval> _instApprovalList = new List<InstanceApproval>();

        private int _instApprovalId;
        private Guid _instId;
        private int _processId;

        private IInstance _instDAL = DALFactory.GetDAL<IInstance>();
        private INode _nodeDAL = DALFactory.GetDAL<INode>();
        private IInstanceApproval _instApprovalDAL = DALFactory.GetDAL<IInstanceApproval>();
        private IForm _formDAL = DALFactory.GetDAL<IForm>();

        protected void Page_Load(object sender, EventArgs e)
        {
            //added by Natalia
            //在主页标题栏上设置标题。
            Master.SetContentTitle("审批流程");


            // url传递 recordId 到本页面
            _recordId = Request.Params["RecordId"];
            this.RequestViewer.RecordId = _recordId;

            LoadData();

            AppendPreviousApprovals();

            if (!IsPostBack)
            {
                
            }
            else
            {
                if (ViewState["_instId"] != null)
                {
                    _instId = new Guid(ViewState["_instId"].ToString());
                }

                if (ViewState["_instApprovalId"] != null)
                {
                    _instApprovalId = Convert.ToInt32(ViewState["_instApprovalId"]);
                }
            }
        }

        private void LoadData()
        {
            _inst = _instDAL.GetInstance(_recordId);
            _instApprovalList = _instApprovalDAL.GetInstanceApprovals(_recordId);
            _processId = _formDAL.GetProcessId(_inst.FormId);
        }


        
        /// <summary>
        /// 动态生成 approval 的页面项目
        /// </summary>
        private void AppendPreviousApprovals()
        {
            foreach (InstanceApproval ia in _instApprovalList)
            {
                // this node has been approved or denied
                if (ia.Step != _inst.Step)
                {
                    UCApprovalView ucAV = (UCApprovalView)Page.LoadControl("/UserControls/UCApprovalView.ascx");
                    ucAV.ApprovalIns = ia;
                    Panel1.Controls.Add(ucAV);
                }
                // this node need to be approved in this step
                else
                {
                    _instApprovalId = ia.Id;

                    UCApprovalForm ucAF = (UCApprovalForm)Page.LoadControl("/UserControls/UCApprovalForm.ascx");
                    if (ia.NodeType != "normal")
                    {
                        ucAF.SubmitButton.Text = "完成";
                        ucAF.CancelButton.Visible = false;
                        ucAF.CloseButton.Visible = false;
                    }


                    ucAF.ProcessId = _processId;
                    ucAF.NodeOrder = ia.NodeOrder;

                    ucAF.SubmitEvent += new EventHandler(SubmitEvent);
                    ucAF.DenyEvent += new EventHandler(DenyEvent);
                    ucAF.CloseEvent += new EventHandler(CloseEvent);
                    ucAF.CancelEvent += new EventHandler(CancelEvent);


                    Panel1.Controls.Add(ucAF);
                }
            }
        }




        #region 事件
        protected void SubmitEvent(object sender, EventArgs e)
        {
            InstanceApproval ia = _instApprovalDAL.GetInstanceApproval(_instApprovalId);
            List<InstanceApproval> iaList = new List<InstanceApproval>();

            bool moveToNext = false;

            if (ia != null)
            {
                ia.IsDenied = false;
                ia.Comment = ((UCApprovalForm)sender).Comments;

                ia.IsApproved = true;
                ia.ApproveDate = DateTime.Now;
                ia.ApproverName = YBPSession.Instance.CurrentUser.Name;
                ia.ApproverId = YBPSession.Instance.CurrentUser.Id;

                

                // 需要更新 instance 的 current node id，current node 需要改为下一个 node
                Node currentNode = _nodeDAL.GetNode(_inst.CurrentNodeId);
                if (currentNode != null)
                {
                    if (currentNode.Condition == 1)
                    {
                        moveToNext = true;
                    }
                    else
                    {
                        // 获取当前已审批通过的总数
                        int approvalAmount = _instApprovalDAL.GetNotDenyAmountByStep(_inst.RecordId.ToString(), _inst.Step);

                        // 如果已审批通过的总数 + 1 (current approval) 大于等于 条件数，则通过
                        if (approvalAmount + 1 >= currentNode.Condition)
                        {
                            moveToNext = true;
                        }
                    }



                    // 可以 move 到下一个 node
                    if (moveToNext)
                    {
                        _inst.Step += 1;

                        Node nextNode = _nodeDAL.GetNextNode(currentNode.ProcessId, currentNode.Order);
                        if (nextNode != null)
                        {
                            _inst.CurrentNodeId = nextNode.Id;
                            _inst.CurrentNodeOrder = nextNode.Order;

                            // 需要生成的下一个node的approval数据
                            iaList = _instApprovalDAL.GetInstanceApprovals(_inst.FormId, _inst.CurrentNodeOrder);
                            // 获取用户选择的下一个node的 审批人
                            List<ApprovalView> approvers = ((UCApprovalForm)sender).Approvers;
                            // 设置步骤
                            //int iStep = _instApprovalDAL.GetCurrentStep(_inst.RecordId);
                            for (int i = 0; i < iaList.Count; i++)
                            {
                                iaList[i].RecordId = ia.RecordId;
                                iaList[i].Step = _inst.Step;
                                iaList[i].ApproveOrder = ia.ApproveOrder + 1;
                                iaList[i].ApproveDate = ConstValue.NullDate;
                                iaList[i].NodeOrder = nextNode.Order;

                                iaList[i].DefaultApproverId = approvers[i].Id;
                                iaList[i].DefaultApprover = approvers[i].ApproverName;
                                iaList[i].IsRole = approvers[i].IsRole;
                            }
                        }
                        else
                        {
                            // 如果没有找到下一个node，则表示当 process 已完成，则关闭当前 instance
                            _inst.IsClosed = true;
                            _inst.CloseDate = DateTime.Now;
                            _inst.ClosedBy = YBPSession.Instance.CurrentUser.Name;
                        }
                    }
                }

                // 保存需要开事务
                _instDAL.Update(_inst, ia, iaList);
            }
        }

        protected void DenyEvent(object sender, EventArgs e)
        {
            //不同意，需要找到回退节点的 approver 来生成 InstanceApprover

            InstanceApproval ia = _instApprovalDAL.GetInstanceApproval(_instApprovalId);
            List<InstanceApproval> iaList = new List<InstanceApproval>();

            bool moveToPre = false;

            if (ia != null)
            {
                ia.IsApproved = false;
                ia.IsDenied = true;
                ia.Comment = ((UCApprovalForm)sender).Comments;

                ia.ApproveDate = DateTime.Now;
                ia.ApproverName = YBPSession.Instance.CurrentUser.Name;
                ia.ApproverId = YBPSession.Instance.CurrentUser.Id;

                // 需要更新 instance 的 current node id，current node id 返回到前一个node
                Node currentNode = _nodeDAL.GetNode(_inst.CurrentNodeId);
                if (currentNode != null)
                {
                    if (currentNode.Condition == 1)
                    {
                        moveToPre = true;
                    }
                    else
                    {
                        // 获取当前已审批通过的总数 + 未审批的总数
                        int notDenyAmount = _instApprovalDAL.GetNotDenyAmountByStep(_inst.RecordId.ToString(), _inst.Step);

                        // 如果已审批通过的总数 + 未审批的总数 - 1 (current approval) 小于 条件数，则回退
                        if (notDenyAmount - 1 < currentNode.Condition)
                        {
                            moveToPre = true;
                        }
                    }

                    if (moveToPre)
                    {
                        _inst.Step += 1;

                        Node preNode = _nodeDAL.GetPreNode(currentNode.ProcessId, currentNode.Order);
                        if (preNode != null)
                        {
                            _inst.CurrentNodeId = preNode.Id;
                            _inst.CurrentNodeOrder = preNode.Order;

                            iaList = _instApprovalDAL.GetInstanceApprovals(_inst.FormId, _inst.CurrentNodeOrder);

                            // 获取上一个step的审批人
                            List<InstanceApproval> instApprovalLastStepList = _instApprovalDAL.GetInstanceApprovalsForLastStep(_inst.RecordId, _inst.Step);

                            for (int i = 0; i < iaList.Count; i++)
                            {
                                iaList[i].RecordId = ia.RecordId;
                                iaList[i].Step = _inst.Step;
                                iaList[i].ApproveOrder = ia.ApproveOrder + 1;
                                iaList[i].ApproveDate = ConstValue.NullDate;
                                iaList[i].ApproverName = "";

                                // 从上一个instance approval获取值
                                iaList[i].DefaultApprover = instApprovalLastStepList[i].DefaultApprover;
                                iaList[i].DefaultApproverId = instApprovalLastStepList[i].DefaultApproverId;
                                iaList[i].NodeType = instApprovalLastStepList[i].NodeType;
                                iaList[i].NodeOrder = instApprovalLastStepList[i].NodeOrder;
                                iaList[i].NodeId = instApprovalLastStepList[i].NodeId;
                                iaList[i].IsRole = instApprovalLastStepList[i].IsRole;
                            }
                        }
                        else
                        {
                            _inst.IsSubmitted = false;
                        }
                    }
                    
                }

                // 保存需要开事务
                _instDAL.Update(_inst, ia, iaList);
            }
        }

        protected void CloseEvent(object sender, EventArgs e)
        {
            InstanceApproval ia = _instApprovalDAL.GetInstanceApproval(_instApprovalId);
            List<InstanceApproval> iaList = _instApprovalDAL.GetInstanceApprovals(_inst.RecordId);
            if (ia != null)
            {
                ia.IsApproved = false;
                ia.IsDenied = false;
                ia.Comment = ((UCApprovalForm)sender).Comments;
                ia.ApproveDate = DateTime.Now;
                ia.ApproverId = YBPSession.Instance.CurrentUser.Id;
                ia.ApproverName = YBPSession.Instance.CurrentUser.Name;

                _inst.IsClosed = true;
                _inst.ClosedBy = YBPSession.Instance.CurrentUser.Name;
                _inst.CloseDate = DateTime.Now;

                // 保存需要开事务
                _instDAL.Update(_inst, ia);
            }
        }

        protected void CancelEvent(object sender, EventArgs e)
        {
            Response.Redirect(@"~/Default.aspx");
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // 将属性保存到ViewState中
            ViewState.Add("_instId", _instId);
            ViewState.Add("_instApprovalId", _instApprovalId);
        }
        #endregion
    }
}